//
//  QLAllInvitedMeetVC.m
//  神约
//
//  Created by qlwl on 17/2/8.
//  Copyright © 2017年 qlwl. All rights reserved.
//

#import "QLAllInvitedMeetVC.h"
#import "QLPublishPopView.h"
#import "QLPublishPopView2.h"
#import "QLPublishLifeInvitatVC.h"
#import "QLPublishSelectPayTypeVC.h"
#import "QLPublishLifeClassifyVC.h"
#import "QLPublishCircleFriendsVC.h"
#import "UIAlertController+AlertController.h"
#import "WYVideoCompressTools.h"
#import <AVFoundation/AVFoundation.h>
#import "QLAllInvitedMeetListCell.h"
#import "QLAllInvitedMeetListModel.h"
#import "QLInvitedMeetDetialVC.h"

@interface QLAllInvitedMeetVC ()
@property (weak, nonatomic) IBOutlet UITableView *tableView1;
@property (weak, nonatomic) IBOutlet UITableView *tableView2;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@end

@implementation QLAllInvitedMeetVC
{
    NSMutableArray * _dataArray1;
    NSMutableArray * _dataArray2;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _dataArray1 = [[NSMutableArray alloc] init];
    _dataArray2 = [[NSMutableArray alloc] init];
    
    [self netWorkingWithPayType:1];
    [self netWorkingWithPayType:2];
}

#pragma mark btnClick
- (IBAction)topBtn1Click:(id)sender {
    [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}
- (IBAction)topBtn2Click:(id)sender {
    [self.scrollView setContentOffset:CGPointMake(iphoneWidth, 0) animated:YES];
}


#pragma mark TabDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView1) {
        return _dataArray1.count;
    }else{
        return _dataArray2.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    QLAllInvitedMeetListCell * cell = [tableView dequeueReusableCellWithIdentifier:@"QLAllInvitedMeetListCell"];
    QLAllInvitedMeetListModel * meetModel = nil;
    if (tableView == self.tableView1) {
        meetModel = _dataArray1[indexPath.row];
    }else{
        meetModel = _dataArray2[indexPath.row];
    }
    [cell.headIma QL_setImageWithURL:[NSString stringWithFormat:@"%@%@",HTTP_BaseURL,meetModel.headpicurl] placeholderImage:nil];
    cell.nameLab.text = meetModel.userName;
    NSString * ageStr = nil;
    if (meetModel.sex.length > 0) {
        ageStr = [meetModel.sex intValue] == 0?@"女":@"男";
    }
    if (meetModel.age.length > 0) {
        ageStr = [NSString stringWithFormat:@"%@%@岁",ageStr,NotNullClass(meetModel.age)];
    }
    cell.ageLab.text = ageStr;
    cell.distanceLab.text = [NSString stringWithFormat:@"%.2fkm",meetModel.distince/1000];
    cell.addressLab.text = meetModel.destination;
    cell.thingLab.text = meetModel.typeName;
    cell.priceLab.text = [NSString stringWithFormat:@"%f元",meetModel.servicePrice];
    if (meetModel.sex.length >0) {
        cell.sexLab.text = [meetModel.sex intValue] == 0?@"女":@"男";
    }else{
        cell.sexLab.text = @"男女不限";
    }
    
    if (meetModel.picList.count > 0) {
        cell.ima1.hidden = NO;
        [cell.ima1 QL_setImageWithURL:[NSString stringWithFormat:@"%@%@",HTTP_BaseURL,[meetModel.picList firstObject]] placeholderImage:nil];
    }else{
        cell.ima1.hidden = YES;
    }
    if (meetModel.picList.count > 1) {
        cell.ima2.hidden = NO;
        [cell.ima2 QL_setImageWithURL:[NSString stringWithFormat:@"%@%@",HTTP_BaseURL,meetModel.picList[2]] placeholderImage:nil];
    }else{
        cell.ima1.hidden = YES;
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    QLAllInvitedMeetListModel * meetModel = nil;
    if (tableView == self.tableView1) {
        meetModel = _dataArray1[indexPath.row];
    }else{
        meetModel = _dataArray2[indexPath.row];
    }
    
    QLInvitedMeetDetialVC * detailVC = [NSString instantiateViewControllerWithIdentifier:@"QLInvitedMeetDetialVC" andSBName:@"Home"];
    [self.navigationController pushViewController:detailVC animated:YES];
    
}


#pragma mark
- (IBAction)addPublishBtnClick:(id)sender {
    QLPublishPopView * publish = [QLPublishPopView showInWindow];
    publish.publishBtnClick = ^(int tag){
        if (tag == 1) {
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet andCancelAction:^{
                
            } andOtherAction:^(int tag) {
                [self selectImaWithType:PickerVideoSourceType + tag];
            } cancelButtonTitle:@"取消" otherButtonTitles:@"小视频",@"拍照",@"从手机相册选择",nil];
            [self presentViewController:alert animated:YES completion:nil];
        }else if (tag == 2){
//            QLPublishLifeInvitatVC * invitatVC = [NSString instantiateViewControllerWithIdentifier:@"QLPublishLifeInvitatVC" andSBName:@"Home"];
//            [self.navigationController pushViewController:invitatVC animated:YES];
            QLPublishLifeClassifyVC * classifyVC = [NSString instantiateViewControllerWithIdentifier:@"QLPublishLifeClassifyVC" andSBName:@"Home"];
            classifyVC.category = 1;
            [self.navigationController pushViewController:classifyVC animated:YES];
        }else if (tag == 3){
            QLPublishPopView2 * publish2 = [QLPublishPopView2 showInWindow];
            publish2.publishBtnClick = ^(int tag){
                if (tag == 1) {
                    //我要求助
                    QLPublishLifeClassifyVC * classifyVC = [NSString instantiateViewControllerWithIdentifier:@"QLPublishLifeClassifyVC" andSBName:@"Home"];
                    classifyVC.category = 2;
                    [self.navigationController pushViewController:classifyVC animated:YES];
                }else if (tag == 2){
                    //我要帮助
                    QLPublishLifeClassifyVC * classifyVC = [NSString instantiateViewControllerWithIdentifier:@"QLPublishLifeClassifyVC" andSBName:@"Home"];
                    classifyVC.category = 3;
                    [self.navigationController pushViewController:classifyVC animated:YES];
                }
            };
        }
    };

}

#pragma mark PickerController 相机相册
- (void)finishImagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info andType:(PickerControllerSourceType)type andMediaURL:(NSURL *)url
{
    if (type==PickerVideoSourceType) {
        NSString * mediaPath = [url path];
        
        [SVProgressHUD QLShowWithStatus:@"视频压缩中" maskType:SVProgressHUDMaskTypeClear];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSString * mp4Path = [self changeVideoToMap4WithVideoURL:[NSURL URLWithString:mediaPath]];
            [WYVideoCompressTools compressVideoWithSourceVideoPathString:mp4Path CompressType:AVAssetExportPresetMediumQuality CompressSuccessBlock:^(NSString *compressVideoPathString) {
                if (compressVideoPathString) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        NSMutableArray * resouceArray = [[NSMutableArray alloc] init];
                        if(mediaPath){
                            [resouceArray addObject:compressVideoPathString];
                        }
                        QLPublishCircleFriendsVC * publishCircelVC = [NSString instantiateViewControllerWithIdentifier:@"QLPublishCircleFriendsVC" andSBName:@"Discover"];
                        publishCircelVC.resouceArray = resouceArray;
                        publishCircelVC.resouceType = PublishResouceMedia;
                        publishCircelVC.publishFinishAndRefresh = ^{
                            
                        };
                        NSLog(@"%@",publishCircelVC.publishFinishAndRefresh);
                        UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:publishCircelVC];
                        [picker dismissViewControllerAnimated:YES completion:^{
                            [self presentViewController:nav animated:YES completion:nil];
                        }];
                        [SVProgressHUD dismiss];
                    });
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [picker dismissViewControllerAnimated:YES completion:^{
                            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"视频压缩失败了!" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
                            UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:(UIAlertActionStyleDefault) handler:nil];
                            [alertController addAction:confirmAction];
                            [self presentViewController:alertController animated:YES completion:nil];
                        }];
                        [SVProgressHUD dismiss];
                    });
                    [self removeVideoWithVideoPath:mp4Path];
                }
                [self removeVideoWithVideoPath:mp4Path];
            } CompressFailedBlock:^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [picker dismissViewControllerAnimated:YES completion:^{
                        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"视频压缩失败了!" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
                        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:(UIAlertActionStyleDefault) handler:nil];
                        [alertController addAction:confirmAction];
                        [self presentViewController:alertController animated:YES completion:nil];
                    }];
                    [SVProgressHUD dismiss];
                });
                [self removeVideoWithVideoPath:mp4Path];
            } CompressNotSupportBlock:^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [picker dismissViewControllerAnimated:YES completion:^{
                        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"不支持当前压缩格式哦!" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
                        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:(UIAlertActionStyleDefault) handler:nil];
                        [alertController addAction:confirmAction];
                        [self presentViewController:alertController animated:YES completion:nil];
                    }];
                    [SVProgressHUD dismiss];
                });
                [self removeVideoWithVideoPath:mp4Path];
            }];
        });
    }else if (type==PickerAlbumSourceType||type==PickerCameraSourceType){
        NSMutableArray *picArray=[[NSMutableArray alloc] init];
        [picArray addObject:[info objectForKey:@"UIImagePickerControllerOriginalImage"]];
        
        QLPublishCircleFriendsVC * publishCircelVC = [NSString instantiateViewControllerWithIdentifier:@"QLPublishCircleFriendsVC" andSBName:@"Discover"];
        publishCircelVC.publishFinishAndRefresh = ^{
            
        };
        publishCircelVC.resouceArray = picArray;
        publishCircelVC.resouceType = PublishResoucePic;
        UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:publishCircelVC];
        [picker dismissViewControllerAnimated:YES completion:^{
            [self presentViewController:nav animated:YES completion:nil];
        }];
    }
}
- (void)finishAssetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSMutableArray *)picArray
{
    //图片
    
}

- (void)failImagePickerControllerDidCancel:(UINavigationController*)picker
{
    
}

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender
{
    return NO;
}

#pragma mark netWorking
- (void)netWorkingWithPayType:(int)chargeType //1免费,2收费
{
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc] init];
    QLLoginModel * loginModel = [QLLoginModel accountFromSandbox];
    postDict[@"userid"] = loginModel.userId;
    postDict[@"currentPage"] = @"1";
    postDict[@"pageSize"] = @"10";
    postDict[@"category"] = @"1";
    postDict[@"chargeType"] = [NSNumber numberWithInt:chargeType];
//    postDict[@""] = @"";
//    postDict[@""] = @"";
//    postDict[@""] = @"";
    [QLNetWorking postJSONWithUrl:QLAllPublishLifeListURl parameters:postDict isJosnRequest:YES rogress:nil success:^(id result) {
        NSLog(@"%@",result);
        //
        if ([QLNetWorking sucess:[result objectForKey:@"mobileHead"] and:@"code" EqualToString:@"success"]) {
            NSArray * array = [QLAllInvitedMeetListModel mj_objectArrayWithKeyValuesArray:[[result objectForKey:@"mobileBody"] objectForKey:@"data"]];
            if (chargeType == 1) {
                [_dataArray1 addObjectsFromArray:array];
                [self.tableView1 reloadData];
            }else if(chargeType == 2){
                [_dataArray2 addObjectsFromArray:array];
                [self.tableView2 reloadData];
            }
        }
    } fail:^(NSError *error) {
        
    }];
}


@end


